<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<center>
    <h3 id="inMsg"></h3>
    <br>
    <br>
    <br>
    <br>
    <h3 id="outMsg"></h3>
</center>
<input type="hidden" id="current_user" value="{$users}">
</body>
<script src="__CHAT__/jquery.min.js"></script>
<script>
    var current_user = eval('(' + $("#current_user").val() + ')');
    var ws = new WebSocket("ws://127.0.0.1:8282"); //实例化

    //打开
    ws.onopen = function () {
        bindUid(); //绑定用户id
        checkUserLine();//查询出来所有在线的用户
    };

    //监听返回的消息
    ws.onmessage = function (e) {
        var data = eval('(' + e.data + ')');
        // console.log(data.user_id);
        switch (data.type) {
            case 'OnLine':
                onLine(data);
                return;
            case 'outLine':
                outLine(data);
                return;
            case 'userCheckUserLine':
                postCheckUserLine(data.data);
                return;
            case 'connect':
                console.log(data);
                return;
        }
    };

    //ajax 异步请求绑定
    function bindUid() {
        var send_message = '{"type":"bindUid","user_id":"' + current_user.id + '","nick_name":"' + current_user.nick_name + '"}';
        ws.send(send_message);
    }

    function checkUserLine() {
        var send_message = '{"type":"userCheckUserLine"}';
        ws.send(send_message);
    }

    //上线
    function onLine(data) {
        // console.log(data);
        $("#inMsg").html(data.nick_name + '刚刚' + data.data);
        $.post("{:url('onLine')}",{'user_id':data.user_id,'click_id':data.client_id});
    }

    //离线
    function outLine(data) {
        // $("#outMsg").html(data.nick_name+'=刚刚'+data.data);
        // console.log(data);
        // $.post("{:url('outLine')}",{'client_id':data.client_id},function(data){
        //     console.log(data);
        // })
    }
    function postCheckUserLine(data){
        // console.log(data);
        $.post("{:url('postCheckUserLine')}",data);
    }
</script>
</html>